package yang.yu.sunny.utils;

import org.apache.commons.dbcp2.BasicDataSource;
import org.dayatang.configuration.Configuration;
import org.dayatang.configuration.ConfigurationFactory;
import org.dayatang.dbunit.DbUnitUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by yyang on 15/8/5.
 */
public class DbHelper {

    private DataSource dataSource;

    private DbUnitUtils dbUnit;

    private String dir = "src/test/resources/";

    public DbHelper() {
        dataSource = createDataSource();
    }


    @Before
    public void setUp() {
        if (dataSource == null) {
            dataSource = createDataSource();
        }
    }

    @After
    public void tearDown() throws SQLException {
        if (dataSource == null) {
            return;
        }
        if (dataSource instanceof BasicDataSource) {
            ((BasicDataSource) dataSource).close();
        }
    }

    private DataSource createDataSource() {
        Configuration configuration = new ConfigurationFactory().fromClasspath("/jdbc.properties");
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(configuration.getString("jdbc.driverClassName"));
        dataSource.setUrl(configuration.getString("jdbc.url"));
        dataSource.setUsername(configuration.getString("jdbc.username"));
        dataSource.setPassword(configuration.getString("jdbc.password"));
        return dataSource;
    }

    @Test
    public void exportDTD() {
        dbUnit = new DbUnitUtils(dataSource);
        dbUnit.exportDtd(dir, "dataset.dtd");
    }

    @Test
    public void exportData() {
        dbUnit = new DbUnitUtils(dataSource);
        dbUnit.exportData(dir, "sample-data.xml");
    }

    @Test
    public void importData() {
        dbUnit = new DbUnitUtils(dataSource);
        dbUnit.importDataFromClasspath("/sample-data.xml");
    }

}
